//
//  NewsTableViewController.m
//  
//
//  Created by admin on 17/3/2.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "NewsTableViewController.h"
#import <AFNetworking.h>
#import "NetworkTool.h"
#import <YYModel.h>
#import "NewsModel.h"
#import <YYModel.h>
#import "NewsTableViewCell.h"
#import "NSDictionary+Data.h"
#import "LCNewsHTMLViewController.h"
#import "NewsTableViewController+LoadData.h"
#import <PAWebView.h>
@interface NewsTableViewController () <UIScrollViewDelegate>

@property (nonatomic,strong) NSMutableArray *selectedData;

@property (assign,  nonatomic) bool isPop;

@end

@implementation NewsTableViewController 

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_isPop) {
        [self.tableView reloadData];//执行POP的方法，比如你POP回来后需要刷新表格。
    }else{
        //执行PUSH进来时的方法。
    }
    _isPop=YES;//将标志设置为YES。
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _isPop=YES;//将标志设置为YES。

    [self setupTableView];
    [self setupMJRefresh];//添加下拉刷新
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lcDidSelectChannelAtCid:) name:@"didSelectChannelAtCid" object:nil];
}

- (void)lcDidSelectChannelAtCid:(NSNotification *)notification {
    if (self.cid == notification.userInfo[@"cid"] && _dataSource == nil) {
        self.url = self.cid;
    }
}

- (NSMutableArray<NewsModel *> *)dataSource{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)setupTableView {
    // 注册cell
//    [self.tableView registerNib:[UINib nibWithNibName:@"BaseCell" bundle:nil] forCellReuseIdentifier:@"BaseCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RightCell" bundle:nil] forCellReuseIdentifier:@"RightCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ImagesCell" bundle:nil] forCellReuseIdentifier:@"ImagesCell"];
    ///当我们的数据未能显示满一屏幕的时候，UITableView会显示多余的横线
    self.tableView.tableFooterView = [[UIView alloc] init];
//    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"头条背景"]];
//    imgView.frame = self.view.bounds;
//    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//    [self.tableView setBackgroundView:imgView];

}

- (void)setupMJRefresh {
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    MJRefreshGifHeader *refreshGifHeader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];    
    MJRefreshNormalHeader *refreshNormalHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//    // 隐藏时间
//    refreshGifHeader.lastUpdatedTimeLabel.hidden = YES;
//    [refreshNormalHeader setTitle:@"加载了n条新数据" forState:MJRefreshStateNoMoreData];
//    refreshNormalHeader.titl
//    MJRefreshStateNoMoreData
    // 设置header
    self.tableView.mj_header = refreshNormalHeader;
    // 上拉刷新
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.edgesForExtendedLayout = UIRectEdgeNone;//就可以正常
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreComments];
//        [self.tableView.mj_footer endRefreshing];
    }];
}
-(void)loadMoreComments{
//    NSLog(@"self.theloadData");
    ///上拉加载数据, 刷新UI;
    [self loadData:self.cid page:YES];
}
-(void)loadNewData{
    ///加载数据, 刷新UI;
    [self loadData:self.cid page:NO];
}
-(void)setCid:(NSString *)cid{
    _cid = cid;
//    NSLog(@"NewsVC = %@",cid);
//    [self loadData:cid page:NO];
}
-(void)setUrl:(NSString *)url{
    _url = url;
    [self loadData:url page:NO];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (_dataSource.count && [_dataSource[0].cid isEqualToString:self.cid]) {
//        self.tableView.mj_footer.hidden = NO;
//        return _dataSource.count;
//    }
//        self.tableView.mj_footer.hidden = YES;
//        return 0;
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsModel *news = _dataSource[indexPath.row];
    NSString *identifier;
    // 根据每行不同的模型数据,选择展示对应的cell的样式
    if (news.cover.count > 2) {
        identifier = @"ImagesCell";
    }else{
        identifier = @"RightCell";
    }
    NewsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[NewsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
     // 获取cell对应的模型数据
    cell.news = news;
        
//    NSLog(@"cell.news.url = %@", cell.news.url);
//    NSLog(@"cell.news.title = %@", cell.news.title);
    if (indexPath.row == 0 && [PAWebView shareInstance].link == nil) {
        [self performSelector:@selector(loadWebDataWithName:) withObject:_dataSource[0].url/*可传任意类型参数*/];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}
//
//- (void)setupWebDataWithName {
//    [self performSelector:@selector(loadWebDataWithName:) withObject:_dataSource[0].url/*可传任意类型参数*/];
//}

//- (void)setupWebWithName:(NSString *)name {
//    [PAWebView shareInstance].view.hidden = YES;
//    [[[UIApplication sharedApplication].delegate window] addSubview:[PAWebView shareInstance].view];
//    [PAWebView shareInstance].view.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, ScreenHeight-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT+(iPhoneX ? 10.f : 0.f));
//    [PAWebView shareInstance].webView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT+(iPhoneX ? 10.f : 0.f));
//    CGRect barFrame = CGRectMake(0,0, ScreenHeight, 2);
//    [PAWebView shareInstance].wkProgressView.frame = barFrame;
//    [PAWebView shareInstance].wkProgressView.progressTintColor = defaultColor;
//}

#pragma mark -  加载网页  -
- (void)loadWebDataWithName:(NSString *)name {
    [PAWebView shareInstance].link = name;
    [[PAWebView shareInstance] loadRequestURL:[NSURL URLWithString:name]];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsModel *news = _dataSource[indexPath.row];
//    [PAWebView shareInstance].webView.hidden = YES;
    [PAWebView shareInstance].webView.allowsBackForwardNavigationGestures = NO;
    [self performSelector:@selector(loadWebDataWithName:) withObject:news.url];
//    [self performSelector:@selector(setupWebWithName:) withObject:news.url/*可传任意类型参数*/];
//    LCNewsHTMLDetailsVC *viewController = [[LCNewsHTMLDetailsVC alloc] init];
//    viewController.url = news.url;
    
    [self.selectedData addObject:news.title];
    [[NSUserDefaults standardUserDefaults] setObject:self.selectedData.copy forKey:@"selectedData"];
    LCNewsHTMLViewController *viewController = [[LCNewsHTMLViewController alloc] init];
    viewController.url = news.url;
    [self.navigationController pushViewController:viewController animated:YES];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
}

-(NSMutableArray *)selectedData{
    if (_selectedData == nil) {
        _selectedData = [NSMutableArray array];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"selectedData"] != nil) {
            [_selectedData addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedData"]];
        }
    }
    return _selectedData;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 获取cell对应的模型数据
    NewsModel *news = _dataSource[indexPath.row];
    
    CGFloat cellH = 80;
    
    // 根据每行不同的模型数据,选择展示对应的cell的样式
    if (news.cover.count > 2) {
        cellH = 160;
    }
    if(news.cover.count == 1) {
        cellH = 130;
    }
    if(news.cover.count == 2) {
        cellH = 130;
    }
    
    return cellH;
}

@end
